

package com.example.lyxxx.music;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends Activity implements View.OnClickListener, MusicApi {

    private TextView before, pause, next, currentSong, startTime, endTime;//播放按钮的监听
    private RecyclerView songRecy;//歌曲列表
    private List<MusicBean> musicList = new ArrayList<>();
    private MusicApdater musicAdapter;
    private SeekBar progress;//歌曲的播放进度
    public static MainActivity mainActivity;
    private boolean ifTouchBar = false;

    private Handler proHandler = new Handler();
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            sendBroadcast(new Intent().setAction(BroadCastBean.bcMusicPro));
            proHandler.postDelayed(this, 1000);
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initVivew();
        initMonitor();
        mainActivity = this;
    }


    private void initMonitor() {
        //歌曲列表的监听事件
        musicAdapter.setOnItemClickListener(new MusicApdater.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                sendBroadcast(new Intent().setAction(BroadCastBean.bcReplay).putExtra("newPosition", position));
                Log.i("输出", "adapter" + position + "路径" + musicList.get(position).getPath() + "");
            }
        });

        //拖动歌曲进度条的事件监听
        progress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                ifTouchBar = true;
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                //发送广播，参数为拖动进度条的进度
                sendBroadcast(new Intent().setAction(BroadCastBean.bcSetMusicPro).putExtra("musicPro",
                        seekBar.getProgress() * 1000));
                ifTouchBar = false;
            }
        });
    }

    @Override
    protected void onResume() {
        proHandler.postDelayed(runnable, 1000);
        startService(new Intent(MainActivity.this.getApplicationContext(), PlayServer.class));
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        stopService(new Intent(MainActivity.this.getApplicationContext(), PlayServer.class));
        super.onDestroy();
    }

    private void initVivew() {
        currentSong = (TextView) findViewById(R.id.main_currentsong);
        startTime = (TextView) findViewById(R.id.main_starttime);
        endTime = (TextView) findViewById(R.id.main_endtime);
        progress = (SeekBar) findViewById(R.id.main_seekBar);
        before = (TextView) findViewById(R.id.main_left);
        before.setOnClickListener(this);
        pause = (TextView) findViewById(R.id.main_pause);
        pause.setOnClickListener(this);
        next = (TextView) findViewById(R.id.main_right);
        next.setOnClickListener(this);
        songRecy = (RecyclerView) findViewById(R.id.main_songRecy);
        songRecy.setLayoutManager(new LinearLayoutManager(MainActivity.this, LinearLayoutManager.VERTICAL, false));
        musicAdapter = new MusicApdater(MainActivity.this, musicList);//歌曲适配器初始化
        songRecy.setAdapter(musicAdapter);
        musicAdapter.notifyDataSetChanged();
        if (MusicUtils.getMusiclist(MainActivity.this) != null) {
            //如果本地歌曲存在的情况
            List<MusicBean> cacheList = MusicUtils.getMusiclist(MainActivity.this);
            BroadCastBean.musicList = cacheList;//全局变量musiclist的重新赋值
            musicList.clear();//清空适配器list，避免重复的数据
            for (int i = 0; i < cacheList.size(); i++) {
                musicList.add(new MusicBean(
                        cacheList.get(i).getSinger(),//歌手名字
                        cacheList.get(i).getSong(),//歌曲名字
                        cacheList.get(i).getPath(),//歌曲路径
                        cacheList.get(i).getDuration(),//歌曲时长
                        cacheList.get(i).getSize()//歌曲大小
                ));
            }
            musicAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.main_left:
                //播放上一首
                if (PlayServer.position == 0) {
                    Toast.makeText(MainActivity.this, "已经是第一首了", Toast.LENGTH_SHORT).show();
                } else {
                    sendBroadcast(new Intent().setAction(BroadCastBean.bcNextOrBefore).
                            putExtra("nobPosition", 1));
                    proHandler.removeCallbacks(runnable);
                }
                break;
            case R.id.main_pause:
                //播放暂停or继续
                sendBroadcast(new Intent().setAction(BroadCastBean.bcPlayOrPause));
                break;
            case R.id.main_right:
                //播放下一首
                if (PlayServer.position == musicList.size() - 1) {
                    Toast.makeText(MainActivity.this, "已经是最后一首了", Toast.LENGTH_SHORT).show();
                } else {
                    sendBroadcast(new Intent().setAction(BroadCastBean.bcNextOrBefore).
                            putExtra("nobPosition", 2));
                    proHandler.removeCallbacks(runnable);
                }
                break;
        }
    }


    //音乐播放信息回调
    @Override
    public void MusicInfo(long begin, String song, long end) {
        currentSong.setText(song);
        startTime.setText(toMinuteSecond(begin));
        endTime.setText(toMinuteSecond(end));
        this.progress.setMax((int) (end / 1000));
        //启动轮询线程不断发送广播进行更新ui
        proHandler.postDelayed(runnable, 1000);
    }

    @Override
    protected void onPause() {
        proHandler.removeCallbacks(runnable);
        super.onPause();
    }

    //音乐播放进度接口回调
    @Override
    public void MusicDuration(long duration) {
        startTime.setText(toMinuteSecond(duration));
        if (!ifTouchBar)
            progress.setProgress((int) (duration / 1000));
    }

    //音乐播放完成接口回调
    @Override
    public void MusicPlayFinish(boolean success) {
        if (success) {
            Toast.makeText(MainActivity.this, "播放完成", Toast.LENGTH_SHORT).show();
            if (PlayServer.position == musicList.size() - 1) {
                Toast.makeText(MainActivity.this, "已经是最后一首了", Toast.LENGTH_SHORT).show();
            } else {
                sendBroadcast(new Intent().setAction(BroadCastBean.bcNextOrBefore).
                        putExtra("nobPosition", 2));
            }
        }
    }


    //时间格式转换函数
    public static String toMinuteSecond(long duration) {
        String time = "";

        long minute = duration / 60000;
        long seconds = duration % 60000;

        long second = Math.round((float) seconds / 1000);

        if (minute < 10) {
            time += "0";
        }
        time += minute + ":";

        if (second < 10) {
            time += "0";
        }
        time += second;

        return time;
    }
}